import OSS from 'ali-oss';

// OSS配置接口
export interface OSSConfig {
  region: string;
  accessKeyId: string;
  accessKeySecret: string;
  bucket: string;
  endpoint?: string;
  secure?: boolean;
  timeout?: number;
}

// 验证必要的环境变量
const requiredEnvVars = [
  'ALIYUN_OSS_REGION',
  'ALIYUN_OSS_ACCESS_KEY_ID', 
  'ALIYUN_OSS_ACCESS_KEY_SECRET',
  'ALIYUN_OSS_BUCKET'
];

const missingEnvVars = requiredEnvVars.filter(varName => !process.env[varName]);
if (missingEnvVars.length > 0) {
  console.warn(`⚠️  阿里云OSS配置不完整，缺少环境变量: ${missingEnvVars.join(', ')}`);
  console.warn(`   OSS功能将无法正常工作，请在.env文件中配置这些变量`);
}

// OSS配置
export const ossConfig: OSSConfig = {
  region: process.env.ALIYUN_OSS_REGION || 'oss-cn-hangzhou',
  accessKeyId: process.env.ALIYUN_OSS_ACCESS_KEY_ID || '',
  accessKeySecret: process.env.ALIYUN_OSS_ACCESS_KEY_SECRET || '',
  bucket: process.env.ALIYUN_OSS_BUCKET || '',
  endpoint: process.env.ALIYUN_OSS_ENDPOINT, // 可选，用于自定义域名
  secure: process.env.ALIYUN_OSS_SECURE === 'true' || true, // 默认使用HTTPS
  timeout: parseInt(process.env.ALIYUN_OSS_TIMEOUT || '60000') // 60秒超时
};

// 创建OSS客户端实例
export const createOSSClient = (): OSS | null => {
  try {
    if (!ossConfig.accessKeyId || !ossConfig.accessKeySecret || !ossConfig.bucket) {
      console.warn('⚠️  OSS配置不完整，无法创建客户端');
      return null;
    }

    const client = new OSS({
      region: ossConfig.region,
      accessKeyId: ossConfig.accessKeyId,
      accessKeySecret: ossConfig.accessKeySecret,
      bucket: ossConfig.bucket,
      endpoint: ossConfig.endpoint,
      secure: ossConfig.secure,
      timeout: ossConfig.timeout
    });

    return client;
  } catch (error) {
    console.error('❌ 创建OSS客户端失败:', error);
    return null;
  }
};

// 检查OSS配置是否有效
export const isOSSConfigured = (): boolean => {
  return !!(ossConfig.accessKeyId && ossConfig.accessKeySecret && ossConfig.bucket);
};

// 默认导出OSS客户端
export const ossClient = createOSSClient();